package cn.edu.guet.springmvcdemo.mvc;
/*
 *   @Studio:CHJY · 源梦科技
 *   @Author:lzl
 *   @Ide:IntelliJ IDEA
 *   @Creation time:2021/7/1 20:19
 */




import cn.edu.guet.springmvcdemo.mvc.annotation.Controller;
import cn.edu.guet.springmvcdemo.mvc.annotation.RequestMapping;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

public class Configuration {
    /*
    扫描控制器的包
     */
    public Map<String,ControllerMapping> config(){
        Map<String,ControllerMapping> controllerMappingMaps=new HashMap<String, ControllerMapping>();
        ResourceBundle bundle=ResourceBundle.getBundle("config");//获取资源文件夹里的指定文件
        String controllerPackageName=bundle.getString("controller.package");//获取文件里的指定字段
        String path=controllerPackageName.replace('.','/');
        URI uri=null;
        try {
            uri=Configuration.class.getResource("/"+path).toURI();
            File controllerDirectory=new File(uri);
            String[] controllerFileNames=controllerDirectory.list();
            for(String str:controllerFileNames){
                String controllerClassName=controllerPackageName+"."+ StringUtils.substringBefore(str,".class");
//                System.out.println(controllerClassName);
                Class<?> controllerClass= ClassUtils.getClass(controllerClassName,true);
                if(controllerClass.isAnnotationPresent(Controller.class)){
                    Method[] handleMethods= MethodUtils.getMethodsWithAnnotation(controllerClass, RequestMapping.class);
                    for(Method met:handleMethods){
                        RequestMapping annotation=met.getAnnotation(RequestMapping.class);
                        ControllerMapping controllerMapping=new ControllerMapping(controllerClass,met);
                        controllerMappingMaps.put(annotation.value(),controllerMapping);
                    }
                }
            }

        } catch (URISyntaxException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return controllerMappingMaps;
    }
}
